package com.grieous.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.grieous.biz.UserBiz;
import com.grieous.dao.UserDao;
import com.grieous.domain.PageModel;
import com.grieous.domain.User;

@Service
public class UserBizImpl implements UserBiz {
	private static final AtomicInteger counter = new AtomicInteger();

	@Resource
	private UserDao userDao;
	

	@Override
	public PageModel getUser(Integer pageSize, Integer page) {
		Map<String, Object> map = new HashMap<String, Object>();
		page = page == null ? 1 : page;
		pageSize = pageSize == null ? 3 : pageSize;
		int count = userDao.getUserCount(map);
		map.put("startId", (page - 1) * pageSize);
		map.put("pageSize", pageSize);
		List<User> list = userDao.getUser(map);
		PageModel pm = PageModel.getPageModel(pageSize, page, count, list);
		return pm;
	}

	@Override
	public void saveUser(User user) {
		if (user != null) { 
			if (user.getId() != null && !user.getId().equals("")) {
				userDao.updateUser(user);
			} else {
				int id = counter.getAndIncrement();
				user.setId(id);
				userDao.insertUser(user);
			}
		}

	}

	@Override
	public void delUser(int... userIds) {
		if (userIds != null) {
			for (int i = 0; i < userIds.length; i++) {
				int userid = userIds[i];
				userDao.deleteUser(userid);
			}
		}

	}

	@Override
	public User getUserById(int id) {
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("id", id);
		List<User> list= userDao.getUser(map);
		if(list!=null && list.size()==1){
			return list.get(0);
		}
		return null;
	}
}
